package com.app.util.printer;

import java.util.Arrays;

public class Progress {

	private Printer printer = new Printer();
	private String title;

	private int minValue = 0;
	private int maxValue = 100;

	private int value;

	private char[] cs = new char[40];

	public Progress(String title) {
		this.title = title;
	}

	public Progress() {
		this(""); 
	}

	public void setWidth(int width) {
		if (width < 0 || width > 1024) {
			throw new RuntimeException("width can not small than 0 and more than 1024");
		}
		cs = new char[width];
	}

	public void setBound(int minValue, int maxValue) {
		if (minValue >= maxValue) {
			throw new RuntimeException("MinValue can not more than maxValue!");
		}
		this.minValue = minValue;
		this.maxValue = maxValue;
	}

	public void setMaxValue(int maxValue) {
		if (minValue >= maxValue) {
			throw new RuntimeException("MaxValue can not small than minValue");
		}
		this.maxValue = maxValue;
	}

	public int getValue() {
		return value;
	}

	public void addValue(int value) {
		setValue(this.value + value);
	}

	public void setValue(int value) {
		this.value = value;
		if (this.value < minValue) {
			this.value = minValue;
		}
		if (this.value > maxValue) {
			this.value = maxValue;
		}
	}

	public void print() {
		printer.print(title + progressBar());
	}

	public void print(String msg) {
		printer.print(title + " " + progressBar() + " " + msg);
	}

	public void clear() {
		printer.print("");
	}

	public int percent() {
		float per = (float) value / maxValue * 100;
		return Math.round(per);
	}

	private String progressBar() {
		int per = percent();
		if (cs.length == 0) {
			return per + "%";
		} else {
			int offset = Math.round((float) per / 100 * cs.length);
			Arrays.fill(cs, 0, offset, '#');
			Arrays.fill(cs, offset, cs.length, '-');
			return "[" + String.valueOf(cs) + "]" + per + "%";
		}
	}

	public int getMinValue() {
		return minValue;
	}

	public int getMaxValue() {
		return maxValue;
	}

	public String getTitle() {
		return title;
	}

	public static void main(String[] args) {
		Progress pp = new Progress("测试");
		pp.setBound(1, 6);
		pp.setWidth(0);
		for (int i = 0; i <= 10; i++) {
			pp.setValue(i);
			pp.print();
		}
	}
}
